package managers
{
	import com.leebrimelow.starling.StarlingPool;
	
	import core.Assets;
	import core.Game;
	
	import objects.Bullet;
	
	import states.Play;

	public class BulletManager
	{
		private var _play:Play;
		private var _bullets:Vector.<Bullet>
		private var _pool:StarlingPool;
		private var _count:uint;
		private var _fireRate:uint;
		private var _bulletSpeed:uint;
		
		public function BulletManager(play:Play)
		{
			this._play = play;
			
			_bullets = new Vector.<Bullet>();
			
			_pool = new StarlingPool(Bullet, 100);
			
			_fireRate = 10;
			_count = 0;
			_bulletSpeed = 280;
		}
		
		public function update(deltaSmall:Number):void
		{
			//trace(_bullets.length);
			var b:Bullet;
			var len:int = _bullets.length - 1;
			for (var i:int = len; i >= 0; i--)
			{
				b = _bullets[i];
				b.y -= _bulletSpeed * deltaSmall;
				
				if (b.y <= -b.height * 0.5)
				{
					destroyBullet(b, i);
				}
			}
			
			/**
			 * The player should be able to fire immediately when he/she pressed the fire key.
			 * */
			if (_play.fire)
			{
				if (_count == 0)
				{
					fire();
				}
				
				// have to make sure _count doesn't = 0 or else we will be firing two bullets
				if (_count != 0 && _count % _fireRate == 0)
				{
					fire();
				}
				
				_count++;
			}
			else
			{
				_count = 0;
			}
		}
		
		/**
		 * "Destroy's" the object.  Don't use .removeChild() or .dispose() because we need to re-pool this object.
		 * */
		public function destroyBullet(b:Bullet, i:int):void
		{
			// move off stage since we are not using .removeChild()
			b.x = -100;
			b.y = -100;
			
			// return the object to the pool
			_pool.returnSprite(b);
			
			// remove the object from the vector to stop animations etc.
			_bullets.splice(i, 1);
		}
		
		/**
		 * Used to destroy the whole class.
		 * */
		public function destroy():void
		{
			for (var i:uint = 0; i < _bullets.length; i++)
			{
				_play.removeChild(_bullets[i]);
				_bullets[i].destroy();
				_bullets.splice(i, 1);
			}
			_bullets = null;
			_pool.destroy();
			_play = null;
		}
		
		public function fire():void
		{
			if (_bullets.length >= 100)
			{
				trace("Cannot create anymore bullets");	
				return;
			}
			
			Game.SOUND_MANAGER.item(Assets.PLAY_PLAYER_SHOOT).play();
			
			var bullet:Bullet = _pool.getSprite() as Bullet;
			_play.addChild(bullet);
			bullet.x = _play.hero.x;
			bullet.y = _play.hero.y - _play.hero.width * 0.5 - bullet.width * 0.5 + 15;
			_bullets.push(bullet);
		}
		
		public function get bullets():Vector.<Bullet>
		{
			return _bullets;
		}

		public function set bullets(value:Vector.<Bullet>):void
		{
			_bullets = value;
		}
	}
}



































